package com.zhongmai.yzfgrabanorder.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import android.widget.Toast;

import com.zhongmai.yzfgrabanorder.view.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpXUtils {
    //    String Url = "http://192.168.1.205:8080/grabOrder/login/login.jhtml";
    //    RequestParams params = new RequestParams(Url);
    //    JSONObject json = new JSONObject();
    //                try {
    //        json.put("loginName", "zyw001");
    //        json.put("loginPwd", "111111");
    //        String key = "LdgOQEGIXyU56scp9u5kr3I1";
    //        String iv = "88323502";
    //        String def = EncryptUtils.encrypt(json.toString(), key, iv);
    //        String mdf = EncryptUtils.md5(def + key).toUpperCase();
    //        Log.d("-------------",def+"------>>>>>>>>>>>>>>>>>>"+mdf);
    //        params.addBodyParameter("def", def);
    //        params.addParameter("mdf", mdf);
    //    } catch (Exception e) {
    //
    //        e.printStackTrace();
    //    }
    //                HttpXUtils.xUtilsPostRequest(LoginActivity.this, params, new HttpXUtils.MyCallback() {
    //        @Override
    //        public void myResult(String result) {
    //            showToast(result);
    //        }
    //    });
    public static int DEFAULT_CACHE_EXPIRY_TIME = 30 * 1000;
    private static LoadingDialog dialog;

    public static void xUtilsPostRequest(final Context context, RequestParams params, final MyCallback callback,
                                         final boolean isloading) {

        if (params == null) {
            params = new RequestParams();
        }

        params.setCacheMaxAge(1000 * 0); //为请求添加缓存时间
        params.setConnectTimeout(DEFAULT_CACHE_EXPIRY_TIME);
        final String url = params.getUri();
        SSLContext sslContext = getSSLContext(context);
        if (null == sslContext) {
            return;
        }

        if (isloading) {
            ((Activity) context).runOnUiThread(new Runnable() {
                public void run() {
                    dialog = new LoadingDialog(context);
                    dialog.show();
                }
            });
        }
        params.setSslSocketFactory(sslContext.getSocketFactory());
        x.http().post(params, new Callback.CacheCallback<String>() {
            private String result = null;

            @Override
            public void onSuccess(String result) {
                LogUtils.bugMes("成功提示。。。。。。" + result, 4);
                if (result != null) {
                    this.result = result;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtils.bugMes("错误提示。。。。。" + String.valueOf(ex.getMessage()), 4);
                Toast.makeText(x.app(), "网络异常", Toast.LENGTH_LONG).show();
                if (isloading && dialog.isShow()) {
                    dialog.dismiss();
                }
                callback.onError(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinished() {
                boolean b = errCodeHandle(context, result);
                if (isloading && dialog.isShow()) {
                    dialog.dismiss();
                }
                if (b) {
                    callback.myResult(result);
                }
            }

            @Override
            public boolean onCache(String result) {
                //                this.result = result;
                return false;
            }
        });
    }

    /**
     * 处理请求后的错误
     *
     * @param context
     * @param result
     * @return
     */
    private static boolean errCodeHandle(Context context, String result) {
        boolean flag = true;
        try {
            JSONObject jsonObject = null;
            jsonObject = new JSONObject(result);
            String code = jsonObject.getString("code");
            if (code.equals(Constants.loginExpiredCode)) {
                LogUtils.bugMes("返回登录页...");
                Utils.save2SP(context, Constants.sp_File, Constants.userToken, "");
                Constants.handle_order_id = "";
                LogUtils.showToast(jsonObject.getString("message"));
                //                context.startActivity(new Intent(context, LoginActivity.class));
                ((Activity) context).finish();
                flag = false;
            } else if (code.equals(Constants.errorCode)) {
                LogUtils.showToast("服务错误");
                flag = false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return flag;
    }

    private static SSLContext mSSLContext = null;

    /**
     * 获取Https的证书
     *
     * @param context 上下文
     * @return SSL的上下文对象
     */
    private static SSLContext getSSLContext(Context context) {
        //        CertificateFactory certificateFactory = null;
        //        InputStream inputStream = null;
        //        Certificate cer = null;
        //        KeyStore keystore = null;
        //        TrustManagerFactory trustManagerFactory = null;
        try {
            //            certificateFactory = CertificateFactory.getInstance("X.509");
            //            inputStream = context.getAssets().open("baidu.cer");//这里导入SSL证书文件
            //            try {
            //                cer = certificateFactory.generateCertificate(inputStream);
            //                Log.i("getSSLContext", cer.getPublicKey().toString());
            //            } finally {
            //                inputStream.close();
            //            }

            //            //创建一个证书库，并将证书导入证书库
            //            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            //            keystore.load(null, null); //双向验证时使用
            //            keystore.setCertificateEntry("trust", cer);
            //
            //            // 实例化信任库
            //            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            //            trustManagerFactory.init(keystore);

            mSSLContext = SSLContext.getInstance("TLS");
            //            mSSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

            //信任所有证书 （官方不推荐使用）
            mSSLContext.init(null, new TrustManager[]{new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {

                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {

                }
            }}, new SecureRandom());

            return mSSLContext;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public interface MyCallback {
        void myResult(String result);

        void onError(String err);
    }
}
